package com.imooc;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Administrator on 2020/2/10.
 */
public class CrosFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletResponse res=(HttpServletResponse) servletResponse;

        HttpServletRequest req=(HttpServletRequest) servletRequest;

//        支持带cookie的请求
        String origin=req.getHeader("Origin");
        if (!org.springframework.util.StringUtils.isEmpty(origin)){
            //      带cookie的时候，origin必须是全匹配，不能用*
            res.addHeader("Access-Control-Allow-Origin",origin);
        }


//      res.addHeader("Access-Control-Allow-Origin","*");

//      res.addHeader("Access-Control-Allow-Methods","GET");
        res.addHeader("Access-Control-Allow-Methods","*");

//        支持所有自定义头
        String headers=req.getHeader("Access-Control-Request-Headers");
        if (!org.springframework.util.StringUtils.isEmpty(headers)){
            //      带cookie的时候，origin必须是全匹配，不能用*
            res.addHeader("Access-Control-Allow-Headers",headers);
        }

        res.addHeader("Access-Control-Allow-Headers","content-type,x-header1,x-header2");

//      缓存预检命令1小时，在缓存时间段内去掉  res.addHeader("Access-Control-Allow-Methods","*")
//      res.addHeader("Access-Control-Allow-Headers","content-type");请求任然有效，去掉缓存将失效
        res.addHeader("Access-Control-Max-Age","3600");

//      enable cookie
        res.addHeader("Access-Control-Allow-Credentials","true");

        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
